import React, { Component } from 'react'
import { Select } from 'antd'
import _ from 'lodash'

const { Option } = Select

class MultiColumnInput extends Component {
  constructor(props) {
    super(props)
    this.state = {
      content: props.content,
      defaultVal: [],
      formatContent: [],
      dataId: 1,
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.content !== this.state.content) {
      this.setState({
        content: nextProps.content,
      }, () => {
        // 处理策略内容格式
        this.formatContentFn()
      })
    }
  }

  componentDidMount() {
    // 处理策略内容格式
    this.formatContentFn()
  }

  addAndFn = (id, e) => {
    e.stopPropagation()
    let { formatContent } = this.state
    formatContent.map(item => {
      if (item.id === id) {
        item.children.push('')
        item.childDisplay.push('')
      }
      return item
    })
    this.setState({
      formatContent,
    })
    this.triggerChange(formatContent)
  }

  addOrFn = () => {
    let { formatContent } = this.state
    const { orgList } = this.props
    const dataId = this.state.dataId + 1
    formatContent.push({
      id: dataId,
      children: [''],
      childDisplay: [''],
      orgs: _.cloneDeep(orgList),
      optional: _.cloneDeep(orgList),
    })
    this.setState({
      formatContent,
      dataId,
    })
    this.triggerChange(formatContent)
  }

  changeSelectAnd = (id, idx, value, options) => {
    let { formatContent } = this.state
    formatContent.map(item => {
      if (item.id === id) {
        let children = item.children
        let childDisplay = item.childDisplay
        let newOrg = item.orgs.filter(org => org.name !== options._name)
        children[idx] = options._name
        childDisplay[idx] = value
        item.optional = newOrg
      }
      return item
    })
    this.setState({
      formatContent,
    })
    this.triggerChange(formatContent)
  }

  triggerChange = (changedValue) => {
    const { onChange } = this.props
    onChange && onChange(changedValue)
  };

  isORpolicy = (content) => {
    if (content.indexOf('OR') > -1) {
      return true
    } else {
      return false
    }
  }

  formatContentFn = () => {
    const { content } = this.state
    const { orgList } = this.props

    if (!content) {
      let { dataId } = this.state
      const formatContent = [
        {
          id: dataId,
          children: [''], // 传的参数
          childDisplay: [''], // 展示的可支持中文
          orgs: _.cloneDeep(orgList), // 所有的 用于删除后补充
          optional: _.cloneDeep(orgList), // 可选项 用户下拉框展示
        },
      ]
      this.setState({
        formatContent,
        dataId: dataId++,
      })
      return false
    }

    const flag = this.isORpolicy(content)
    let ss = null
    if (flag) {
      // 存在OR关系
      ss = content.slice(3, content.length - 1)
    } else {
      // 不存在OR关系
      ss = content
    }
    const arr = ss.split('AND')

    let newArr = []
    let orgsArr = []
    let childDisplay = []
    let dataId = 1
    arr.length && arr.map((item, idx) => {
      if (item) {
        const _list = _.cloneDeep(orgList)
        let child = _.words(item, /[^( || )$ || ^, || ^' || '$ ]+/g) || []

        child = child.map(item => {
          item = item.split('.')[0].slice(0, -3)
          return item
        })

        childDisplay = _.cloneDeep(child).map(item => {
          const displayArr = _list.length && _list.filter(n => n.name === item)
          item = displayArr.length && displayArr[0].display_name
          return item
        })
        _list.length && _list.map(n => {
          if (!child.includes(n.name)) {
            orgsArr.push(n)
          }
        })
        newArr.push({
          id: idx,
          children: child,
          childDisplay,
          orgs: _.cloneDeep(orgList),
          optional: orgsArr,
        })
        dataId = dataId++
      }
    })
    this.setState({
      formatContent: newArr,
      dataId,
    })
    this.triggerChange(newArr)
  }

  deletePeer = (idx, itemIdx, type, flag) => {
    let { formatContent } = this.state
    const newArr = _.cloneDeep(formatContent)
    if (flag) {
      newArr[idx].children[itemIdx] = ''
      newArr[idx].childDisplay[itemIdx] = ''
      newArr[idx].optional = newArr[idx].orgs
      this.setState({
        formatContent: newArr,
      })
      this.triggerChange({ newArr })
      return
    }

    if (type === 'AND') {
      // if(itemIdx == 0 ){
      //     newArr[idx].optional = newArr[idx].orgs;
      // }else{
      newArr[idx].optional = newArr[idx].optional.concat(newArr[idx].orgs.filter(k => k.display_name === newArr[idx].childDisplay[itemIdx]))
      // }
      newArr[idx].children.splice(itemIdx, 1)
      newArr[idx].childDisplay.splice(itemIdx, 1)
      // 如果AND为空
      if (!newArr[idx].children.length) {
        newArr.splice(idx, 1)
      }
    }
    // 重置表单内容
    // this.props._this.form.resetFields();
    this.setState({
      formatContent: newArr,
    })
    this.triggerChange(newArr)
  }

  render() {
    const { formatContent } = this.state
    return (
      <div className="multi-input">
        <div className="multi-tip">每一行条件为or的关系，每一行行内为and关系</div>
        <div className="multi-content">
          <div className="multi-body" ref={ref => this.scrollBody = ref}>
            {
              formatContent.length > 0 &&
              formatContent.map((element, idx) => {
                const childDisplay = element.childDisplay || []
                const ORGS = element.optional || []
                return (
                  <div key={idx} className="input-row">
                    {
                      childDisplay.length > 0 &&
                      childDisplay.map((item, itemIdx) => {
                        return (
                          <div key={itemIdx} className="input-row-item">
                            <img onClick={() => {
                              this.deletePeer(idx, itemIdx, 'AND', idx === 0 && itemIdx === 0 && element.childDisplay.length === 1 && formatContent.length === 1)
                            }} className="delete-icon" src={require('@/images/chaincode/delete_and.svg')} />
                            <Select
                              style={{ width: '100px' }}
                              value={item || '请选择'}
                              placeholder="请选择"
                              onChange={(value, options) => { this.changeSelectAnd(element.id, itemIdx, value, options) }}>
                              {
                                ORGS.map((_ops, _index) => {
                                  return (
                                    <Option key={itemIdx + _index} _name={_ops.name} value={_ops.display_name}>{_ops.display_name || '无'}</Option>
                                  )
                                })
                              }
                            </Select>
                          </div>
                        )
                      })
                    }
                    {
                      element.children.length > 0 &&
                      <div className="add-and" onClick={(e) => { this.addAndFn(element.id, e) }}>添加“and条件”</div>
                    }
                  </div>
                )
              })
            }
          </div>
        </div>
        <div className="add-or">
          <span onClick={() => { this.addOrFn() }}>添加“or条件”</span>
        </div>
      </div>
    )
  }
}
export default MultiColumnInput
